package com.we823.cms.core.security.shiro.realm;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.we823.cms.model.sys.User;
import com.we823.cms.repository.service.sys.UserService;

/**
 * 自定义DB AuthorizingRealm
 * @author ZhangYinxian
 *
 */
public class CmsAuthorizingRealm extends AuthorizingRealm implements ApplicationContextAware {

	private static final Logger logger = LoggerFactory.getLogger(CmsAuthorizingRealm.class);

    private ApplicationContext applicationContext;

    @Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		logger.debug("doGetAuthorizationInfo");
		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		
		UserService userService = applicationContext.getBean(UserService.class);
		if (userService!=null) {
			User userModel = userService.findByUsername(username);
			authorizationInfo.setRoles(userService.findStringRole(userModel));
			Set<String> stringPermissionSet = userService.findStringPermission(userModel);
			authorizationInfo.setStringPermissions(stringPermissionSet);
		}
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException {
		logger.debug("doGetAuthenticationInfo");
		
		if(token!=null){
			String username = (String)token.getPrincipal();
			User userModel = null;
            if(applicationContext.containsBean("userService")) {
                UserService userService = (UserService) applicationContext.getBean("userService");
                if(userService!=null){
                    userModel = userService.findByUsername(username);
                }
            }
			if(userModel!=null){
				SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                        userModel.getUsername(),
                        userModel.getPassword(),
						getName()
						);
				return simpleAuthenticationInfo;
			}
		}
		return null;
	}

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
